package com.shang.dao.impl;

import com.mongodb.client.result.DeleteResult;
import com.shang.dao.UserDao;
import com.shang.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class UserDaoImpl implements UserDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    public List<User> getUsersByPage(int pageNum,int pageSize){
        String collectionName="user";
        if (pageNum!=0){
            pageNum--;
        }
        Pageable pageable= PageRequest.of(pageNum,pageSize);
        Query query=new Query().with(pageable);
        List<User> userList = mongoTemplate.find(query, User.class, collectionName);
        return userList;
    }

    @Override
    public int getUserNumber() {
        List<User> userList = mongoTemplate.find(new Query(), User.class, "user");
        return userList.size();
    }

    @Override
    public int deleteUserByName(String userName) {
        Criteria criteria=new Criteria().where("userName").is(userName);
        Query query=new Query(criteria);
        DeleteResult user = mongoTemplate.remove(query, "user");
        if (user!=null){
            return 1;
        }else {
            return 0;
        }
    }

    public List<User> getUserByName(String userName){
        Criteria criteria=new Criteria("userName").is(userName);
        Query query=new Query(criteria);
        List<User> userList = mongoTemplate.find(query, User.class, "user");
        return userList;
    }

}
